import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:get/get.dart';
import 'package:mziot/app/config/design.dart';
import 'package:mziot/app/modules/home/views/devices_list_view.dart';
import 'package:mziot/app/modules/home/views/group_list_view.dart';
import 'package:mziot/app/routes/app_pages.dart';
import 'package:mziot/app/tools/blue_service.dart';
import 'package:mziot/app/tools/global_const.dart';
import 'package:mziot/app/tools/tools.dart';
import 'package:mziot/generated/assets.dart';
import 'package:mziot/generated/locales.g.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../controllers/home_controller.dart';

class HomeView extends GetView<HomeController> {
  @override
  Widget build(BuildContext context) {
    controller.refreshController = RefreshController();
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: _appBar,
      body: Stack(
        children: [
          Image.asset(
            Assets.imagesListBack,
            width: double.infinity,
            height: double.infinity,
            fit: BoxFit.cover,
          ),
          SafeArea(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.max,
              children: [
                SizedBox(height: 18),
                _typeView,
                Obx(() {
                  if (!controller.isGroup.value) {
                    return _filterView;
                  } else {
                    return Container();
                  }
                }),
                Expanded(
                  child: Obx(
                    () {
                      if (controller.isLoading.value) {
                        return Container();
                      }
                      if (controller.isGroup.value) {
                        return GroupListView();
                      }
                      return DevicesListView(false);
                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  get _appBar {
    return PreferredSize(
      preferredSize: Size.fromHeight(64.0),
      child: Container(
        padding: EdgeInsets.only(top: 20),
        child: AppBar(
          backgroundColor: Colors.transparent,
          systemOverlayStyle: SystemUiOverlayStyle.dark,
          title: _avatarView,
          actions: [_blueItem, menuItem],
          centerTitle: false,
        ),
      ),
    );
  }

  get _avatarView {
    return Container(
      child: Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(20),
            child: Container(
              width: 40,
              height: 40,
              child: CachedNetworkImage(
                imageUrl: GlobalConst.userModel?.userHeadImg ?? 'x',
                placeholder: (ctx, a1) => Image.asset(Assets.imagesLogo, width: 40, height: 40),
                errorWidget: (ctx, a1, a2) => Image.asset(Assets.imagesLogo, width: 40, height: 40),
              ),
            ),
          ),
          SizedBox(width: 8),
          Container(
            width: 120,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  GlobalConst.userModel?.nickName ?? '-',
                  style: MFont.semi_Bold16.apply(color: Colors.white),
                ),
                Text(
                  'Welcome to Home',
                  style: MFont.regular13.apply(color: Colors.white),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  get _blueItem {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        if (!controller.isOpen.value) {
          MPermission.instance.bluetooth();
        }
      },
      child: Container(
        padding: EdgeInsets.only(right: 12),
        child: Obx(() {
          return Image.asset(
            controller.isOpen.value
                ? controller.isConnected.value
                    ? Assets.imagesBlueLink
                    : Assets.imagesBlueUnlink
                : Assets.imagesBlueClose,
            width: 30,
            height: 30,
          );
        }),
      ),
    );
  }

  get menuItem {
    Widget _itemAction(String title, int index) {
      return CupertinoActionSheetAction(
        child: Text(
          title,
          style: MFont.semi_Bold15.apply(color: MColor.xFF000000),
        ),
        isDefaultAction: index == 3 ? true : false,
        onPressed: (() {
          Get.back();
          if (index == 0) {
            Get.toNamed(Routes.ADD_DEVICE)?.then((value) {
              BlueService.share.isAll = false;
              controller.refreshAction();
            });
          } else if (index == 1) {
            Get.toNamed(
              Routes.DEVICE_MANAGER,
              arguments: {
                'group': true,
                'add': true,
                'name': LocaleKeys.add_devices_group_title.tr,
              },
            )?.then((value) => controller.refreshAction());
          } else if (index == 2) {
            Get.toNamed(Routes.SCENE_DETAIL);
          }
        }),
      );
    }

    return GestureDetector(
      onTap: () {
        showCupertinoModalPopup(
            context: Get.context!,
            builder: (ctx) {
              return CupertinoActionSheet(
                actions: [
                  _itemAction(LocaleKeys.home_add_device.tr, 0),
                  _itemAction(LocaleKeys.home_create_group.tr, 1),
                  _itemAction(LocaleKeys.home_create_scene.tr, 2),
                ],
                cancelButton: _itemAction(LocaleKeys.devices_cancel.tr, 3),
              );
            });
      },
      child: Container(
        padding: EdgeInsets.only(right: 12),
        child: Image.asset(Assets.imagesInsertIcon, width: 30, height: 30),
      ),
    );
  }

  get _typeView {
    TextStyle defaultStyle = MFont.regular16.apply(color: MColor.xFF333333);
    TextStyle selectedStyle = MFont.semi_Bold16.apply(color: MColor.xFF333333);

    return Obx(() {
      final isGroup = controller.isGroup.value;
      return Container(
        height: 46,
        margin: EdgeInsets.symmetric(horizontal: 12),
        decoration: BoxDecoration(
          border: Border(bottom: BorderSide(color: MColor.xFF666666, width: 0.5)),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                controller.refreshController = RefreshController();
                if (controller.isGroup.value) {
                  controller.isGroup.value = false;
                  controller.page = 0;
                  controller.refreshAction();
                }
                if (controller.deviceIndex.value == 2) {
                  Future.delayed(Duration(milliseconds: 200), () {
                    controller.scrollController.jumpTo(80);
                  });
                }
              },
              child: Container(
                height: double.infinity,
                width: (Get.width - 24) / 2,
                decoration: isGroup
                    ? null
                    : BoxDecoration(
                        border: Border(bottom: BorderSide(color: MColor.xFF333333, width: 4)),
                      ),
                child: Center(
                  child: Text(
                    LocaleKeys.home_tab_devices.tr,
                    style: !isGroup ? selectedStyle : defaultStyle,
                  ),
                ),
              ),
            ),
            Expanded(
              child: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  controller.refreshController = RefreshController();
                  if (!controller.isGroup.value) {
                    controller.isGroup.value = true;
                    controller.refreshAction();
                  }
                },
                child: Container(
                  height: double.infinity,
                  width: (Get.width - 24) / 2,
                  decoration: isGroup
                      ? BoxDecoration(
                          border: Border(bottom: BorderSide(color: MColor.xFF333333, width: 4)),
                        )
                      : null,
                  child: Center(
                    child: Text(
                      LocaleKeys.home_tab_group.tr,
                      style: isGroup ? selectedStyle : defaultStyle,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  get _filterView {
    return Container(
      height: 28,
      margin: EdgeInsets.only(top: 23),
      child: ListView.builder(
        itemCount: 3,
        scrollDirection: Axis.horizontal,
        controller: controller.scrollController,
        itemBuilder: (ctx, index) {
          if (index == 0) {
            return _filterItem(0, LocaleKeys.home_all_devices.tr);
          } else if (index == 1) {
            return _filterItem(1, LocaleKeys.home_in_group.tr);
          } else {
            return _filterItem(2, LocaleKeys.home_out_group.tr);
          }
        },
      ),
    );
  }

  Widget _filterItem(int index, String text) {
    return Obx(() {
      final isSelected = index == controller.deviceIndex.value;
      final selectedStyle = BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
      );
      final defaultStyle = BoxDecoration(
        color: Colors.white.withOpacity(0.2),
        borderRadius: BorderRadius.circular(14),
      );

      return GestureDetector(
        onTap: () {
          if (index != controller.deviceIndex.value) {
            controller.deviceIndex.value = index;
            controller.fetchDevices();
            double offset = 0;
            if (index > 1) {
              offset = 80;
            }
            controller.scrollController
                .animateTo(offset, duration: Duration(milliseconds: 200), curve: Curves.ease);
          }
        },
        child: Container(
          height: 28,
          margin: EdgeInsets.only(left: index == 0 ? 14 : 0, right: 14),
          padding: EdgeInsets.symmetric(horizontal: 24),
          decoration: isSelected ? selectedStyle : defaultStyle,
          child: Center(
            child: Text(
              text,
              style: isSelected
                  ? MFont.semi_Bold15.apply(
                      color: MColor.xFF48A23F,
                    )
                  : MFont.regular15.apply(
                      color: Colors.white,
                    ),
            ),
          ),
        ),
      );
    });
  }
}
